import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';
import moment from 'moment';
import AMUIReact,{
    Button,
    Input,
    Form,
    Icon
} from 'amazeui-react';

import Fetch from '../common/Fetch';

class UserGroup extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data:{},
            pur_list:[],
            page:{
                pageSize:20,
                currentPage:1,
                totalNum:43
            },
            upload_img:'',
            is_save:false,
            type:this.props.params.id ? 'edit':'add',
            init:false
        };
    }

    componentDidMount() {
        if (this.state.type === 'edit') {
            this.refs.modal.load('正在加载数据...');
            Fetch('/admin/group_manage/get_group',{id:this.props.params.id},(res)=>{
                if (res.status) {
                    this.setState({
                        data:res.data,
                        pur_list:res.data.grp_pur
                    });
                    this.refs.modal.closeModal();
                } else {
                    this.refs.modal.alert('提示','加载分组数据出错',()=>{
                        this.context.router.push('/user_group');
                        return true;
                    });
                }
            },()=>{
                this.refs.modal.alert("提示","远程调用失败");
            });
        }
    }

    saveGroup = ()=>{
        var data = this.checkData();
        if (data === false) return;
        if (this.state.is_save) return;
        this.setState({
            is_save:true
        });
        this.refs.modal.load('正在保存数据...');
        Fetch('/admin/group_manage/save',data,(res)=>{
            if (res.status) {
                this.refs.modal.alert('成功','保存分组数据成功!',()=>{
                    this.context.router.push('/user_group');
                });
            } else {
                this.refs.modal.alert('失败','保存分组失败!!');
                this.setState({
                    is_save:false
                });
            }
        },()=>{
            this.refs.modal.alert('失败','远程调用失败!!');
            this.setState({
                is_save:false
            });
        });
    };

    changeHandler(field){
        return (e)=>{
            var info = this.state.data;
            info[field] = e.target.value;
            this.setState({data:info});
        }
    }

    checkData() {
        var valid = {
            'grp_name':{role:'s2-20',errmsg:'分组名称为2到20个字符'},
            'grp_eng_name':{role:'*2-30',errmsg:'分组英文名称为2到30个字符'},
            'grp_pur':{role:'*',errmsg:'分组权限不能为空'}
        };
        var data = {};
        $.map(this.refs,(item,key)=>{
            if (/^grp/.test(key)) {
                let field = item.props.field || key;
                data[field] = item.getValue();
            }
        });
        data['grp_pur'] = this.state.pur_list
        if (this.state.type === 'edit') {
            data['grp_id'] = this.props.params.id;
        }
        try {
            Validate.inst().checkData(data,valid);
            return data;
        } catch (e) {
            this.refs.modal.alert('错误',e);
            return false;
        }
    }

    openPur = ()=> {
        this.refs.modal.view('权限选择','purview',{pur:this.state.pur_list},(pur)=>{
            var data = this.state.data;
            data['grp_pur'] = pur;
            this.setState({
                data:data,
                pur_list:pur
            });
        });
    };

    render() {
        var data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.type==='edit'?'修改分组':'添加分组'} back={true}/>
                <div className="content_main">
                    <div style={{marginBottom:'20px'}}>
                        <h4 className="title">分组信息</h4>
                    </div>
                    <Form ref="from" horizontal style={{marginTop:'20px'}}>
                        <Input id="grp_name" ref="grp_name" label="分组名称"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.grp_name}
                               placeholder="分组名称为2到20个字符"
                               onChange={this.changeHandler('grp_name')}
                        />
                        <Input id="grp_pur_str" ref="grp_pur_str" label="分组权限" labelClassName="am-u-sm-2"
                               disabled
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.grp_pur}
                               onChange={this.changeHandler('grp_pur')}
                               placeholder="请选择权限分组"
                               btnAfter={<Button onClick={this.openPur}>选择权限</Button>}
                        />
                        <Input label="创建时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.created_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                    </Form>
                    <div className="am-form-group">
                        <div className="am-u-sm-2">
                            &nbsp;
                        </div>
                        <div className="am-u-sm-4 am-u-end">
                            <Button amStyle="primary"
                                    onClick={this.saveGroup}
                                    disabled={this.state.is_save}
                            >
                                {this.state.is_save?'保存中...':'保存'}
                            </Button>
                        </div>
                    </div>
                </div>
                <CKModal ref="modal"/>
            </div>
        );
    }
}


UserGroup.contextTypes = {
    router: React.PropTypes.object
};

export default UserGroup;